function [schidx,nsidx] = ContextDetectionTraining(sch,schidx)
% [schidx,nsidx] = ContextDetectionTraining(sch,schidx)
%
%  

%  Takes the schedule and schidx as input.
%       SCH is the schedule structure
%       SCHIDX is a 1D matrix with the number of rows equal to the number
%           of unique trials; i.e. size(trials,1).
%  Returns an updated version of SCHIDX and NSIDX
%       NSIDX is the next schedule trial index, i.e. the next index
%           selected from the SCH.trials matrix to run.
%       SCHIDX should be updated with the number of runs for each unique
%           trial in SCH.trials.  The returned version should have
%           SCHIDX(NSIDX) incremented.
%
%  This same format for input and output paramters must be met for custom
%  trial select functions (i.e., experiment.trialselectfcn);
%
%  DJS (c) 2011

% global G_RP


if ~isfield(sch,'trial_idx'), sch.trial_idx = 1; end
trials = sch.trials;
% boxid  = sch.boxid;


rv = sch.response_vals;

if isempty(rv)
    nsidx = 1;
    schidx = zeros(size(trials,1),1);
    schidx(nsidx) = 1;
    return
end

rcidx = regexp(sch.readparams,'response_code');
rcidx = findincell(rcidx) + 1;

vals = rv(:,rcidx);

miss = bitget(vals(end),5);

if miss
    nsidx = rv(end,1);
else
    nsidx = rv(end,1) + 1;
end

if nsidx > length(schidx), nsidx = 1; end

% update SCHIDX
schidx(nsidx) = schidx(nsidx) + 1;









